package com.wmf.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求资源路径
        String path = request.getServletPath();
        HttpSession session = request.getSession();
        //3.判断是否包含登录相关资源路径
        // 获取登录状态
        String flag = (String) session.getAttribute("flag");
        /* 判断是否是登录页、首页、登录servlet */
        if (path != null && (path.equals("/view/login.jsp") || path.equals("/index.jsp") || path.equals("/userServlet") || path.equals("/view/register.jsp"))) {
            // 是则直接转发到下一组件
            filterChain.doFilter(request, response);
        } else {
            // 否，则验证登录状态
            if (flag != null) {
                if (flag.equals("loginsucc")) {
                    // 登录成功，直接转发到下一组件
                    filterChain.doFilter(request, response);
                } else {
                    // 登录失败，跳转到登录页，并保证当前网页的url文件路径
                    request.setAttribute("msg", "登录失败");
                    request.setAttribute("return_uri", path);
                    RequestDispatcher rd = request.getRequestDispatcher("/view/login.jsp");
                    rd.forward(request, response);
                }
            } else {
                // 未登录，跳转到登录页，并保证当前网页的url文件路径
                request.setAttribute("msg", "您尚未登录，请登录");
                request.setAttribute("return_uri", path);
                RequestDispatcher rd = request.getRequestDispatcher("/view/login.jsp");
                rd.forward(request, response);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
